<template>
    <div class="container">
        <img src="@/assets/img/putBg.png" alt="" style="width: 60%; margin-left: 25%;">
        <p>请扫描试管上的条形码，请勿漏扫！</p>
        <Table :columns="columns" :scroll="{ y: 520 }" :data-source="TableData" :pagination="false" bordered
            style="min-height: 9rem;">
            <template #bodyCell="{ record, column }">
                <template v-if="column.dataIndex === 'groupName'">
                    <div>
                        <span style="margin-right:.1875rem">{{ record.groupName }}</span>
                        <CloseCircleFilled style="color:red" @click="remove(record.id)" />
                    </div>
                </template>
            </template>
            <template #footer>
                <div style="text-align: right">
                    <Button type="primary" @click="open">确定</Button>
                    <Button type="default" @click="goBack">取消</Button>
                </div>
            </template>
        </Table>
    </div>
</template>
<script setup lang="ts">
import { CloseCircleFilled } from '@ant-design/icons-vue'
import { Table, Button } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { isAndroid } from '@/utils/UtilFun'
import { onMounted, onUnmounted, reactive, ref, toRaw } from 'vue'

import { db } from '@/utils/DexieDB'
import { queryServiceInfoApi } from '@/API/API'

const router = useRouter()
const obj = router.currentRoute.value.query

const testTube = {
    name: '姓名',
    sex: '性别',
    groupName: '标本名称',
}

const idx = ref(0)
const deviceInstance = ref<device | null>(null)

const columns = [
    {
        title: '姓名',
        dataIndex: 'name',
        align: 'center' as const,
    },
    {
        title: '性别',
        dataIndex: 'sex',
        align: 'center' as const,
    },
    {
        title: '标本名称',
        dataIndex: 'groupName',
        align: 'center' as const,
    },
]
const TableData = ref<testTube[]>([])
let keySequence = ''
let keypressTimeout: number | null = null;


function remove(id: number) {
    TableData.value = TableData.value.filter(item => item.index !== id)
}

// 开门
async function open() {
    const addDataId: number[] = []


    if (isAndroid()) {
        // window.ClosetAndroid.openTrackLock();
        window.ClosetAndroid.openTrack();
        window.ClosetAndroid.ttsStop();

        deviceInstance.value!.used += TableData.value.length

        await db.device.update(1, { ...deviceInstance.value })



        Promise.all(TableData.value.map(async (item) => {
            // const id = await db.addData('putTable', item)

            // 检查是否已存在相同的 info
            const existingRecord = await db.testTube.where('info').equals(item.info).first();

            let id: number | undefined;
            if (existingRecord) {
                // 如果存在相同 info，则更新记录
                await db.testTube.update(existingRecord.id, { ...item });
                await db.testTubeHistory.add({ ...item })
                id = existingRecord.id;
            } else {
                // 如果不存在相同 info，则添加新记录
                id = await db.testTube.add({ ...item });
                await db.testTubeHistory.add({ ...item });
            }

            console.log(id);

            if (id !== undefined) {
                addDataId.push(id);
            } else {
                console.warn('添加数据失败，返回 id 为 undefined');
            }
        })).then(() => {
            console.log('添加数据成功id字符串:', JSON.stringify(addDataId));
            window.ClosetAndroid.takePhoto('put');
            router.push({ name: 'OpenDoor', query: { data: JSON.stringify(addDataId) } })
        }).catch((err) => {
            console.log('添加数据失败:', err);
        })
    }
}

function goBack() {
    if (isAndroid()) {
        window.ClosetAndroid.ttsStop();
    }
    router.back()
}


function handleKeyup(e: KeyboardEvent) {
    // 清除之前的定时器
    if (keypressTimeout) {
        clearTimeout(keypressTimeout);
    }

    if (e.key !== "Enter") {
        keySequence += e.key;
        // 设置新的定时器，在一定时间内没有按键则认为输入完成
        keypressTimeout = setTimeout(() => {
            console.log('超时自动处理，最终代码:', keySequence);
            handleCode();
        }, 100); // 100ms无新输入则处理
    } else {
        // 按下Enter键时立即处理
        console.log('扫描完成，最终代码:', keySequence);
        handleCode();
    }
}

function handleCode() {

    if (keySequence) {
        const filterData = TableData.value.filter(item => item.info === keySequence)
        if (filterData.length > 0) {
            window.ClosetAndroid.ttsSpeak('请勿重复扫码！', 1);
            keySequence = ''
            return
        }

        db.info.where({ info: keySequence }).first().then(infoData => {
            console.log('本地数据库查询info', infoData);
            console.log('handleCode', keySequence);
            if (infoData) {
                const objData = {
                    index: idx.value++,
                    name: infoData.name,
                    sex: infoData.sex,
                    info: infoData.info,
                    age: infoData.age,
                    groupName: infoData.groupName,
                    putTime: getTime(),
                    outTime: '',
                    jianchamingcheng: infoData.jianchamingcheng,
                    specimenName: infoData.specimenName,
                }
                const { index, info, age, jianchamingcheng, specimenName, putTime, outTime, ...objWithoutId } = objData;
                TableData.value.push(objData)
                const text = translateKeys(objWithoutId)
                window.ClosetAndroid.ttsSpeak(`${text}`, 1);
            } else if (keySequence === '11111111' || keySequence === '22222222' || keySequence === '33333333' || keySequence === '44444444') {
                const objData = {
                    index: idx.value++,
                    name: '张三',
                    sex: '男',
                    age: 18,
                    info: keySequence,
                    groupName: '粪便常规',
                    putTime: getTime(),
                    outTime: '',
                    jianchamingcheng: '粪便常规',
                    specimenName: '粪便',
                }
                const { index, info, age, jianchamingcheng, specimenName, putTime, outTime, ...objWithoutId } = objData;
                TableData.value.push(objData)
                const text = translateKeys(objWithoutId)
                window.ClosetAndroid.ttsSpeak(`${text}`, 1);
            } else {
                queryServiceInfo()
            }
        })
    }

    // 清除定时器
    if (keypressTimeout) {
        clearTimeout(keypressTimeout);
        keypressTimeout = null;
    }
}

// 本地无试管信息时 询问平台试管信息
function queryServiceInfo() {
    queryServiceInfoApi({
        info: keySequence
    }).then(async ({ code, data }) => {
        console.log('查询平台info信息成功:', data);
        if (data) {
            const objData = {
                index: idx.value++,
                name: data.name,
                sex: data.sex,
                age: data.age,
                info: keySequence,
                groupName: data.groupName,
                putTime: getTime(),
                outTime: '',
                jianchamingcheng: data.jianchamingcheng,
                specimenName: data.specimenName,
            }
            const { index, info, putTime, outTime, ...objWithoutId } = objData;
            TableData.value.push(objData)
            const text = translateKeys(objWithoutId)
            window.ClosetAndroid.ttsSpeak(`${text}`, 1);
        } else {
            window.ClosetAndroid.ttsSpeak('未查询到有效信息，请联系护士站', 1);
            keySequence = ''
        }
    })
}


// 添加一个函数来将英文键替换为中文键
function translateKeys(data: Record<string, any>): string {
    const result: Record<string, any> = {};
    for (const key in data) {
        if (testTube.hasOwnProperty(key)) {
            result[testTube[key as keyof typeof testTube]] = data[key];
        } else {
            result[key] = data[key];
        }
    }
    return Object.entries(result)
        .map(([key, value]) => `${key}:${value}`)
        .join(',');
}

onMounted(async () => {
    document.addEventListener("keyup", handleKeyup);
    deviceInstance.value = await db.device.get(1) as device;

    console.log('进入了扫码页面');
    // console.log(deviceInstance.value);


    if (isAndroid()) {
        const objData = {
            index: idx.value,
            name: obj.name as string,
            sex: obj.sex as string,
            info: obj.code as string,
            age: Number(obj.age),
            groupName: '粪便常规',
            putTime: getTime(),
            outTime: '',
            jianchamingcheng: obj.jianchamingcheng as string,
            specimenName: obj.specimenName as string,
        }
        const { index, info, age, jianchamingcheng, specimenName, putTime, outTime, ...objWithoutId } = objData;
        TableData.value.push(objData)
        const text = translateKeys(objWithoutId)
        window.ClosetAndroid.ttsSpeak(`${text}`, 1);
    }
})

onUnmounted(() => {
    document.removeEventListener("keyup", handleKeyup);
})



function getTime() {
    return new Date().toLocaleString('sc-se', {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        hour12: false,
    }).replace(/\//g, '-')
}




</script>
<style lang="scss" scoped>
.container {
    width: 100%;
    height: 100vh;
    background: #445c93;
    padding: .25rem;
    text-align: center;

    p {
        color: #fff;
        font-size: .5rem;
    }
}

:deep(.ant-table-tbody>tr>td) {
    font-size: .325rem;
}

:deep(.ant-table-thead>tr>th) {
    font-size: .375rem;
}

:deep(.ant-table-thead > tr > th),
:deep(.ant-table-tbody > tr > td) {
    padding: .2rem .1rem;
}

:deep(.ant-btn) {
    font-size: .325rem;
    height: auto;
    padding: .125rem .375rem;
}

:deep(.ant-table-footer) {
    position: absolute;
    bottom: 0;
    width: 100%;
}
</style>